package com.choosefine.base.shixiaobao.common.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.stereotype.Component;

/**
 * Created by 王缙光 on 2016/12/23.
 */
@Component
public class CustomizeVariableUtil {


    /**
     * 单层的model
     * @param jsonString  原字符
     * @param paramString 获取的字符模板
     * @return
     */
    public String getModelJSONInString(String jsonString,String paramString){

        return getString(jsonString,getParamsMap(paramString,0));
    }


    /**
     * 单层的list获取模板
     * @param jsonString
     * @param paramString
     * @return
     */
    public String getListJSONInString(String jsonString,String paramString){
        return getString(jsonString,getParamsMap(paramString,1));
    }
    public String getValueJSONInString(String jsonString){
        String str = getString(jsonString,getParamsValue());
        return str.substring(str.indexOf(":")+2,str.length()-2);
    }
    public Map<String,List<String>> getParamsValue(){
        Map<String,List<String>> stringListMap = new HashMap<>();
        List<String> stringList = new ArrayList<>();
        stringList.add("data");
        stringListMap.put("1",stringList);
        return stringListMap;
    }
    public Map<String,List<String>> getParamsMap(String original_data,Integer k){
        Map<String,List<String>> paramsMap = new HashMap<>();
        List<String> list = new ArrayList<>();
        list.add("status");
        list.add("message");
        list.add("data");
        paramsMap.put("1",list);

        String data[] = original_data.split(",");
        List<String> stringList = Arrays.asList(data);
        if(k == 0){
            paramsMap.put("data2",stringList);
        }else{
            List<String> list2 = new ArrayList<>();
            list2.add("total");
            list2.add("list");
            paramsMap.put("data2",list2);



            paramsMap.put("list3",stringList);
        }

        return paramsMap;
    }



    /**
     *字符拼接[将输入的Json字符返回制定的层级参数]
     * @param str 输入的字符
     * @param fm 制定的层级参数
     * @return
     */
    public String  getString(String str,Map<String,List<String>> fm){
        int VALID_LEVEL = 1;//当前有效层级

        int CURRENT_LEVEL = 1;//所在层级  当前字符串
        String STRING_FORMAT_FILTER = getFormatFilter(str);


        //去除最外层大括号
        str = filterString(str,STRING_FORMAT_FILTER);
        str = str.substring(1,str.length()-1);
        String theses_before = "\\{";
        String theses_after = "\\}";
        String rawData[] = str.split(",");
        if (rawData == null || rawData.length <1){
            return str;
        }

        String returnStr = "" + "{";

        Map<Integer,String> keyMap = new HashMap<>();
        keyMap.put(1,"1");
        for(int i = 0;i<rawData.length;i++){

            String s = "";
            String key =  "";//获取的String的属性

            if(VALID_LEVEL == CURRENT_LEVEL && "{".equals(rawData[i].substring(0,1))){
                returnStr += "{";
                VALID_LEVEL += 1;
                CURRENT_LEVEL += 1;
                rawData[i] = rawData[i].substring(1,rawData[i].length());
            }
            s = rawData[i].substring(1,rawData[i].length());
            key =  s.substring(0,s.indexOf(":")-1);//获取的String的属性
            while(fm.containsKey(keyMap.get(CURRENT_LEVEL))&& fm.get(keyMap.get(CURRENT_LEVEL)).contains(key)){
                if( charCountInString(rawData[i],theses_before) <= 0  && charCountInString(rawData[i],theses_after) <= 0  ){
                    returnStr += rawData[i]+",";
                    rawData[i] = null;
                    key = null;
                }else if(charCountInString(rawData[i],theses_before) >0) {
                    int k = 0;
                    if(rawData[i].contains("[")){
                        k = charCountInString(rawData[i],"\\[");
                    }
                    returnStr += rawData[i].substring(0, rawData[i].indexOf(":") + 2 +k);
                    VALID_LEVEL += 1;
                    keyMap.put(VALID_LEVEL,rawData[i].substring(1,rawData[i].indexOf(":")-1)+VALID_LEVEL);
                    rawData[i] = rawData[i].substring(rawData[i].indexOf(":")+2 + k);
                    CURRENT_LEVEL += 1;
                    key =  rawData[i].substring(1,rawData[i].indexOf(":")-1);
                }else if(charCountInString(rawData[i],theses_after) >0 ){
//                    int dd = rawData[i].indexOf("}")+1;
//                    String kk = rawData[i].substring(0,rawData[i].indexOf("}")+1);
                    returnStr += rawData[i].substring(0,rawData[i].indexOf("}")+1);

                    CURRENT_LEVEL -= 1;
                    VALID_LEVEL -= 1;
                    if(rawData[i].length() >(rawData[i].indexOf(theses_after)+1)){
                        rawData[i] = rawData[i].substring(rawData[i].indexOf("}"));
                    }else{
                        rawData[i] = null;
                    }
                    key = rawData[i];
                }
            }

            if(rawData[i] != null && charCountInString(rawData[i],theses_before) >0 ){
                CURRENT_LEVEL += charCountInString(rawData[i],theses_before);
            }

            if(rawData[i] != null && charCountInString(rawData[i],theses_after) >0 ){
                if(VALID_LEVEL == CURRENT_LEVEL){
                    VALID_LEVEL -= charCountInString(rawData[i],theses_after);
                    CURRENT_LEVEL -= charCountInString(rawData[i],theses_after);
                    returnStr = returnStr.substring(0,returnStr.length()-1);

                    returnStr += rawData[i].substring(rawData[i].indexOf("}"));
                    if(VALID_LEVEL >1){
                        returnStr += ",";
                    }
                }else{
                    if(CURRENT_LEVEL -VALID_LEVEL >= charCountInString(rawData[i],theses_after)){
                        CURRENT_LEVEL -= charCountInString(rawData[i],theses_after);
                        rawData[i] = null;
                    }else{
                        returnStr += rawData[i].substring(rawData[i].indexOf("}")-1+CURRENT_LEVEL-VALID_LEVEL);
                        if(VALID_LEVEL >1){
                            returnStr += ",";
                        }
                    }
                }
            }
        }
        if(",".equals(returnStr.substring(returnStr.length()-1,returnStr.length()))){
            returnStr = returnStr.substring(0,returnStr.length()-1);
        }
        returnStr +="}";
        if (returnStr.contains(STRING_FORMAT_FILTER)){
            returnStr = returnStr.replaceAll(STRING_FORMAT_FILTER,",");
        }
        return returnStr;

    }
    public int charCountInString(String str, String key){
        int k = str.length();
        str = str.replaceAll(key,"");
        return k-str.length();
    }

    /**
     * 获取随机字符
     * @param length 字符长度
     * @return
     */
    public String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";//含有字符和数字的字符串
        Random random = new Random();//随机类初始化
        StringBuffer sb = new StringBuffer();//StringBuffer类生成，为了拼接字符串

        for (int i = 0; i < length; ++i) {
            int number = random.nextInt(62);// [0,62)

            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 获得字符串中不存在的一个15位字符
     * @param str
     * @return
     */
    public String getFormatFilter(String str){
        String filter = getRandomString(15);
        while(str.contains(filter)){
            filter = getRandomString(15);
        }
        return filter;
    }
    /**
     * 过滤一些不需要的逗号
     * @param str
     * @param fil
     * @return
     */
    public String filterString(String str,String fil){
        Pattern pattern = Pattern.compile(",[[^\"|^\\{]]");
        Matcher matcher = pattern.matcher(str);

        while(matcher.find()){
            int sta = matcher.start();
            int end = matcher.end();
            str = str.substring(0,sta) + fil + str.substring(end-1);
            matcher = pattern.matcher(str);
        }

        return str;
    }
}
